package cn.fanyamin.servlet;

import java.io.IOException;

import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import javax.servlet.ServletConfig;

import javax.servlet.http.Cookie;



import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.fanyamin.util.EncodeUtils;


public class DebugServlet extends HttpServlet {
// ------------------------------ FIELDS ------------------------------
    private static final Log logger = LogFactory.getLog(DebugServlet.class);

// ------------------------ INTERFACE METHODS ------------------------


// --------------------- Interface Servlet ---------------------

    public void init(final ServletConfig config)
            throws ServletException
    {
        super.init(config);
    }

// -------------------------- OTHER METHODS --------------------------

    public void doGet(
            final HttpServletRequest request,
            final HttpServletResponse response
    )
            throws ServletException, IOException
    {
        doService(request, response);
    }

    public static void doService(
            final HttpServletRequest request,
            final HttpServletResponse response
    )
            throws ServletException, IOException
    {
        try {
            response.setContentType("text/html");

            final StringBuilder htmlOutput = new StringBuilder();
            final StringBuilder debugOutput = new StringBuilder();

            debugOutput.append("DebugServlet invoked; output: ");

            htmlOutput.append("<html>");
            htmlOutput.append("<p><center><b><FONT SIZE=+2>Walter DebugServlet</FONT></b></center>");

            //Cookies
            htmlOutput.append("<p><b>Cookies</b><br>");
            htmlOutput.append("<table border=1 >");
            htmlOutput.append("<tr><th>Name</th><th>Value</th></tr>");

            debugOutput.append("\n**Cookies**\n");
            final Cookie[] cookies = request.getCookies();
            Cookie cookie;
            if (cookies != null) {
                for (final Cookie cooky : cookies) {
                    cookie = cooky;
                    htmlOutput.append("<tr><td>");
                    htmlOutput.append(cookie.getName());
                    htmlOutput.append("</td><td>");
                    htmlOutput.append(cookie.getValue());
                    htmlOutput.append("</td><tr>");
                    debugOutput.append(cookie.getName() + ": " + cookie.getValue());
                }
            }
            htmlOutput.append("</table>");

            //Headers
            htmlOutput.append("<p><b>Request Headers</b><br>");
            htmlOutput.append("<table border=1 >");
            htmlOutput.append("<tr><th>Name</th><th>Value</th></tr>");
            debugOutput.append("\n**Request Headers**\n");

            for (final Enumeration headers = request.getHeaderNames(); headers.hasMoreElements();) {
                final String headerName = (String) headers.nextElement();
                final String headerValue = request.getHeader(headerName);

                htmlOutput.append("<tr><td>");
                htmlOutput.append(headerName);
                htmlOutput.append("</td><td>");
                htmlOutput.append(headerValue);
                htmlOutput.append("</td><tr>");
                debugOutput.append(headerName + ": " + headerValue);
            }

            htmlOutput.append("</table>");

            //Method (GET/POST)
            htmlOutput.append("<p><b>Method</b><br>");
            debugOutput.append("\n**Method**\n");
            htmlOutput.append("Method: " + request.getMethod());
            debugOutput.append("Method: " + request.getMethod());
            htmlOutput.append("<br><input type=submit name=Submit value=Submit><br>");

            //Parameters
            htmlOutput.append("<p><b>Request Parameters</b><br>");
            htmlOutput.append("<table border=1 >");
            htmlOutput.append("<tr><th>Name</th><th>Value</th></tr>");
            debugOutput.append("\n**Request Parameters**\n");
            for (Enumeration parameters = request.getParameterNames(); parameters.hasMoreElements();) {
                final String parameterName = (String) parameters.nextElement();
                final String parameterValue = request.getParameter(parameterName);
                htmlOutput.append("<tr><td>");
                
                htmlOutput.append(parameterName);
                htmlOutput.append("</td><td>");
                htmlOutput.append(EncodeUtils.htmlEncode(parameterValue));
                htmlOutput.append("</td><tr>");
                debugOutput.append(parameterName + ": " + parameterValue + "\n");
            }
            htmlOutput.append("</table>");

            //PathInfo
            htmlOutput.append("<p><b>Path Info</b><br>");
            debugOutput.append("\n**Path Info**\n");
            htmlOutput.append("Path Info: " + request.getPathInfo());
            debugOutput.append("Path Info: " + request.getPathInfo());

            //Path Translated
            htmlOutput.append("<p><b>Path Translated</b><br>");
            debugOutput.append("\n**Path Translated**\n");
            htmlOutput.append("Path Translated: " + request.getPathTranslated());
            debugOutput.append("Path Translated: " + request.getPathTranslated());

            //Query String
            htmlOutput.append("<p><b>Query String</b><br>");
            debugOutput.append("\n**Query String**\n");
            htmlOutput.append("Query String: " + request.getQueryString());
            debugOutput.append("Query String: " + request.getQueryString());

            //Request URI
            htmlOutput.append("<p><b>Request URI</b><br>");
            debugOutput.append("\n**Request URI**\n");
            htmlOutput.append("Request URI: " + request.getRequestURI());
            debugOutput.append("Request URI: " + request.getRequestURI());

            //Servlet Path
            htmlOutput.append("<p><b>Servlet Path</b><br>");
            debugOutput.append("\n**Servlet Path**\n");
            htmlOutput.append("Servlet Path: " + request.getServletPath());
            debugOutput.append("Servlet Path: " + request.getServletPath());

            // -- UIBean --
            htmlOutput.append("<hr/>");

            htmlOutput.append("</form></html>");

            //Output the data to response
            response.getOutputStream().print(htmlOutput.toString());

            //Output the data to debugger.
            logger.info(debugOutput.toString());
        } catch (Throwable e) {
            logger.error("unexpecte error building output",e);
        }
    }

    public void doPost(
            final HttpServletRequest request,
            final HttpServletResponse response
    )
            throws ServletException, IOException
    {
        doService(request, response);
    }
}
